import axios from 'axios';
import { message } from 'antd';
import { BASE_URL } from '../config';

// 设置默认的基础 URL
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:3000/api';

// 创建 axios 实例
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000, // 10秒超时
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加错误处理拦截器
api.interceptors.response.use(
  response => response,
  error => {
    if (error.code === 'ECONNABORTED') {
      message.error('请求超时，请检查网络连接');
    } else if (!error.response) {
      message.error('网络连接失败，请检查网络设置');
    } else {
      message.error('服务器错误，请稍后重试');
    }
    return Promise.reject(error);
  }
);

const discussionApi = {
  // 获取所有已发布的讨论
  getPublishedDiscussions: async () => {
    try {
      const response = await api.get('/discussions?status=published');
      return response.data;
    } catch (error) {
      throw error;
    }
  },

  // 获取讨论详情
  getDiscussionById: async (id) => {
    try {
      const response = await api.get(`/discussions/${id}`);
      return response.data;
    } catch (error) {
      throw error;
    }
  },

  // 点赞讨论
  likeDiscussion: async (id) => {
    try {
      const discussion = await discussionApi.getDiscussionById(id);
      const response = await api.post(`/discussions/${id}/like`);
      return response.data;
    } catch (error) {
      throw error;
    }
  },

  // 添加评论
  addComment: async (discussionId, comment) => {
    try {
      const discussion = await discussionApi.getDiscussionById(discussionId);
      const comments = discussion.comments || [];
      const response = await api.post(`/discussions/${discussionId}/comments`, {
        ...comment,
        id: Date.now()
      });
      return response.data;
    } catch (error) {
      throw error;
    }
  },

  // 获取讨论列表
  getDiscussions: async () => {
    const response = await api.get('/discussions');
    return response.data;
  },

  // 创建讨论
  createDiscussion: async (discussionData) => {
    const response = await api.post('/discussions', discussionData);
    return response.data;
  },

  // 更新讨论
  updateDiscussion: async (discussionId, discussionData) => {
    const response = await api.put(`/discussions/${discussionId}`, discussionData);
    return response.data;
  },

  // 删除讨论
  deleteDiscussion: async (discussionId) => {
    const response = await api.delete(`/discussions/${discussionId}`);
    return response.data;
  },

  // 删除评论
  deleteComment: async (discussionId, commentId) => {
    const response = await api.delete(`/discussions/${discussionId}/comments/${commentId}`);
    return response.data;
  },

  // 取消点赞
  unlikeDiscussion: async (discussionId) => {
    const response = await api.delete(`/discussions/${discussionId}/like`);
    return response.data;
  }
};

export default discussionApi; 